﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Media.Imaging;

namespace WordFlowDocumentCreator
{
    internal class Imaging
    {
        string m_directory;

        System.Windows.ResourceDictionary m_resources;

        internal Imaging(string directory)
        {
            m_directory = directory;
        }

        internal Imaging(System.Windows.ResourceDictionary resources)
        {
            m_resources = resources;
        }

        /// <summary>
        /// If we are saving to a file, then create the image in the directory otherwise add as a BitmapImage resource
        /// </summary>
        /// <param name="fileName">the filename or resource key</param>
        /// <param name="base64">a Base-encoded image</param>
        /// <returns>the source name for the image</returns>
        /// <remarks>Ignore Code Analysis warning AvoidUncalledPrivateCode</remarks>
        public string SaveImage(string fileName, string base64)
        {
            byte[] data = System.Convert.FromBase64String(base64);

            using (System.IO.MemoryStream stream = new System.IO.MemoryStream(data))
            {
                if (string.IsNullOrEmpty(m_directory))
                {
                    BitmapImage bitmapImage = new BitmapImage();

                    bitmapImage.BeginInit();
                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                    bitmapImage.StreamSource = stream;
                    bitmapImage.EndInit();

                    m_resources.Add(fileName, bitmapImage);

                    return "{DynamicResource " + fileName + "}";
                }
                else
                {
                    using (Image image = Image.FromStream(stream))
                    {
                        string fullPath = m_directory + "\\" + fileName.Replace('/', '\\');

                        string directory = System.IO.Path.GetDirectoryName(fullPath);
                        if (!System.IO.Directory.Exists(directory))
                        {
                            System.IO.Directory.CreateDirectory(directory);
                        }

                        image.Save(fullPath);

                        return fileName;
                    }
                }
            }
        }
    }
}
